<template>
  <xh-container btnText="保存" @onSave="handleClickSubmit" title="新增">
    <view class="container">
      <uni-forms
        ref="form1"
        :rules="rules1"
        :modelValue="formData"
        :label-width="80"
        label-align="right"
      >
        <uni-forms-item label="出库时间" name="boundTime">
          <uni-datetime-picker
            type="date"
            v-model="formData.boundTime"
            :start="Date.now()"
          />
        </uni-forms-item>
      </uni-forms>
      <uni-section title="出库表单" type="line">
        <uni-table border stripe emptyText="暂无更多数据">
          <!-- 表头行 -->
          <uni-tr>
            <uni-th align="center" v-for="item in columns" :key="item.title">{{
              item.title
            }}</uni-th>
          </uni-tr>
          <!-- 表格数据行 -->
          <uni-tr v-for="(item, index) in tableData" :key="item.insCode">
            <uni-td align="center">{{ item.productName }}</uni-td>
            <uni-td align="center">
              {{ item.insCode }}
            </uni-td>
            <uni-td align="center">{{ item.validateData }}</uni-td>
            <uni-td align="center">{{ item.volumeNum }}</uni-td>
            <uni-td align="center">{{ item.meters }}</uni-td>
            <uni-td>
              <view class="uni-group">
                <!-- <xh-button size="mini" type="primary"> 修改 </xh-button> -->
                <xh-button
                  size="mini"
                  type="warn"
                  @click="handelClickDel(index)"
                  >删除</xh-button
                >
              </view>
            </uni-td>
          </uni-tr>
        </uni-table>
        <xh-button :borderRadius="0" type="default" @click="handelClickAdd"
          >添加</xh-button
        >
      </uni-section>
      <xh-popup
        title="添加明细"
        ref="xhPopup"
        @ok="handleClickOk"
        @close="handleClickClose"
      >
        <uni-forms
          ref="form2"
          :modelValue="detailData"
          :label-width="90"
          :rules="rules2"
        >
          <uni-forms-item label="产品名称" name="productName">
            <uni-data-select
              v-model="detailData.productCode"
              :localdata="productList"
              @change="handleProductChange"
            ></uni-data-select>
          </uni-forms-item>
          <uni-forms-item label="检验编码" name="insCode">
            <xh-data-select
              v-model="detailData.insCode"
              :localdata="showInspectList"
              @change="onChangeInsCode"
            />
          </uni-forms-item>
          <uni-forms-item label="检验数据" name="validateData">
            <uni-easyinput
              type="text"
              v-model="detailData.validateData"
              placeholder="检验数据"
            />
          </uni-forms-item>
          <uni-forms-item label="卷数（卷）" name="volumeNum">
            <uni-easyinput
              type="text"
              v-model="detailData.volumeNum"
              placeholder="请输入卷数"
            />
          </uni-forms-item>
          <uni-forms-item label="米数（米）" name="meters">
            <uni-easyinput
              type="text"
              v-model="detailData.meters"
              placeholder="请输入米数"
            />
          </uni-forms-item>
        </uni-forms>
      </xh-popup>
    </view>
  </xh-container>
</template>

<script>
import { mapGetters } from "vuex";
import {
  addOutbound,
  getRecordBillProduct,
  getInsCodeList,
} from "@/api/purchase/fabric.js";
import { codeVerificationCheck, formatSelectList } from "@/utils/business.js";
export default {
  data() {
    return {
      formData: {},
      detailData: {},
      tableData: [],
      columns: [
        {
          title: "产品名称",
        },
        {
          title: "检验编号",
        },
        {
          title: "检验数据",
        },
        {
          title: "卷数（卷）",
        },
        {
          title: "米数（米）",
        },
        {
          title: "操作",
        },
      ],
      selectRequest: getInsCodeList,
      inspectList: [],
      showInspectList: [],
      productList: [],
      rules1: {
        factory: {
          rules: [
            {
              required: true,
              errorMessage: "请选择生产厂家",
            },
          ],
        },
        boundTime: {
          rules: [
            {
              required: true,
              errorMessage: "请选择出库时间",
            },
          ],
        },
      },
      rules2: {
        productName: {
          rules: [
            {
              required: true,
              errorMessage: "请选择产品",
            },
          ],
        },
        insCode: {
          rules: [
            {
              required: true,
              errorMessage: "请选择检验编码",
            },
          ],
        },
        volumeNum: {
          rules: [
            {
              required: true,
              errorMessage: "请输入卷数",
            },
            {
              format: "number",
              errorMessage: "请输入数字",
            },
          ],
        },
        meters: {
          rules: [
            {
              required: true,
              errorMessage: "请输入米数",
            },
            {
              format: "number",
              errorMessage: "请输入数字",
            },
          ],
        },
      },
    };
  },
  computed: {
    ...mapGetters(["mobileInboundList"]),
  },
  created() {
    getRecordBillProduct({ pageSize: 100 }).then((res) => {
      const { rows } = res;
      this.productList = formatSelectList(rows || [], {
        text: "productName",
        value: "productName",
      });
    });
  },
  mounted() {},
  methods: {
    // 关闭 添加明细弹窗
    handleClickClose() {
      this.$refs.form2.clearValidate();
      this.detailData = {};
      this.showInspectList = [];
    },
    // 选择检验编码时
    onChangeInsCode(item) {
      console.log("item", item);
      const {
        insCode,
        fabricId,
        auditStatus,
        factory,
        boundType,
        balanceMeters,
        balanceVolumeNum,
        validateData,
      } = item;
      this.detailData = {
        ...this.detailData,
        fabricId: fabricId,
        meters: balanceMeters,
        volumeNum: balanceVolumeNum,
        insCode,
        auditStatus,
        factory,
        boundType,
        validateData,
      };
    },
    // 删除
    handelClickDel(index) {
      this.tableData.splice(index, 1);
    },
    // 提交
    handleClickSubmit() {
      this.$refs.form1
        .validate()
        .then((values) => {
          const beanList = this.tableData.map((item) => {
            const { volumeNum, meters } = item;
            return {
              ...values,
              ...item,
              balanceVolumeNum: volumeNum,
              balanceMeters: meters,
            };
          });
          addOutbound({
            ...values,
            beanList,
            boundType: 0,
          }).then(() => {
            this.$modal.msgSuccess("出库成功！");
            this.clearData();
            this.$nav.navigateBack();
          });
        })
        .catch((err) => {
          console.log("表单错误信息：", err);
        });
    },
    clearData() {
      this.tableData = [];
      this.detailData = {};
      this.formData = {};
    },
    handleProductChange(val) {
      const proItem = this.productList.find((item) => item.productName === val);
      if (proItem) {
        const { productName } = proItem;
        getInsCodeList(productName,'1',null,'1').then((res) => {
          const { rows } = res;
          this.showInspectList = this.formatSelectOptions(rows || []);
        });
        this.detailData.productName = productName;
      } else {
        this.showInspectList = [];
        this.detailData.insCode = "";
        this.detailData.fabricId = null;
        this.detailData.meters = "";
        this.detailData.volumeNum = "";
      }
    },
    formatSelectOptions(arr) {
      return arr?.map((item) => ({
        ...item,
        text: item.insCode,
        value: item.insCode,
      }));
    },
    handleClickOk() {
      this.$refs.form2
        .validate()
        .then(() => {
          codeVerificationCheck(this.tableData, this.detailData).then(() => {
            this.tableData.push(this.detailData);
            console.log("this.tableData", this.tableData);
            this.detailData = {};
            this.$refs.xhPopup.close();
          });
        })
        .catch((err) => {
          console.log("表单错误信息：", err);
        });
    },
    // 添加
    handelClickAdd() {
      this.$refs.xhPopup.open("top");
    },
  },
};
</script>

<style scoped lang="scss">
.container {
  padding: 10px;
}

.popup-title {
  line-height: 45px;
  font-size: 18px;
  font-weight: bold;
  text-align: center;
  height: 45px;
  border-bottom: 1px solid #ccc;
  border-top: 1px solid #ccc;
}

.popup-footer {
  display: flex;

  button {
    flex-grow: 1;
    border-radius: 0;

    &:last-of-type {
      border-left: none;
    }
  }
}

.form-content {
  padding: 10px;
}

.btn-wrapper {
  display: flex;

  button {
    flex-grow: 1;
    border-radius: 0;

    &:last-of-type {
      border-left: none;

      &::after {
        border-left: none;
      }
    }

    &::after {
      border-radius: 0;
    }
  }
}
</style>
